package com.example.bookmall.controller.bookmallSystem;


import com.example.bookmall.entity.Category;
import com.example.bookmall.entity.Result;
import com.example.bookmall.entity.usercore.User;
import com.example.bookmall.service.CategoryService;
import com.example.bookmall.service.UserService;
import com.example.bookmall.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/categorys")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private UserService userService;

    //添加分类
    @PostMapping("/add")
    public Result addCategory(@RequestBody Category category){

        Map<String, Object> map = ThreadLocalUtil.get();
        String userName = (String) map.get("username");
        User currentuser = userService.findByUserName(userName);

        if (currentuser.getRole() == 0||  currentuser.getRole() == 1) {
            return Result.error("权限不足");
        }
        return categoryService. addCategory(category);

    }

    //获取所有分类
    @GetMapping("/list")
    public Result getAllCategories() {
        List<Category> categories = categoryService.getAllCategories();
        return Result.success(categories);
    }


    //获取分类
    @GetMapping("/{categoryId}")
    public Result getCategoryById(@PathVariable Integer categoryId) {
        Category category = categoryService.getCategoryById(categoryId);
        return Result.success(category);
    }

    //修改分类
    @PutMapping("/modfiy")
    public Result updateCategory(@RequestBody Category category) {
        return categoryService.updateCategory(category);
    }

    //删除分类

    @DeleteMapping("/delete/{categoryId}")
    public Result deleteCategory(@PathVariable Integer categoryId) {

        return categoryService.deleteCategory(categoryId);
    }

    @GetMapping("/search")
    public Result searchCategoryByName(@RequestParam String categoryName) {
        if (categoryName == null || categoryName.trim().isEmpty()) {
            return Result.error("分类名称不能为空");
        }
        // 去除分类名称前后空格
        categoryName = categoryName.trim();
        // 根据分类名称查询分类ID
        List<Category> categoryList = categoryService.getCategoryByName(categoryName);
        if (categoryList == null) {
            return Result.error("分类不存在");
        }
        return Result.success(categoryList);
    }
}
